/*
 * *******************************************************************
 *   @项目名称: BHex Android
 *   @文件名称: AssetDetailActivity.java
 *   @Date: 18-11-29 下午4:05
 *   @Author: ppzhao
 *   @Description:
 *   @Copyright（C）: 2018 BlueHelix Inc.   All rights reserved.
 *   注意：本内容仅限于内部传阅，禁止外泄以及用于其他的商业目的.
 *  *******************************************************************
 */

package io.bhex.app.account.ui;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import io.bhex.app.R;
import io.bhex.app.account.presenter.AssetDetailPresenter;
import io.bhex.app.base.BaseActivity;
import io.bhex.app.utils.CommonUtil;
import io.bhex.app.utils.DialogUtils;
import io.bhex.app.utils.IntentUtils;
import io.bhex.app.utils.NetWorkStatus;
import io.bhex.app.utils.NumberUtils;
import io.bhex.app.view.TopBar;
import io.bhex.baselib.constant.AppData;
import io.bhex.baselib.utils.DebugLog;
import io.bhex.baselib.utils.ToastUtils;
import io.bhex.baselib.view.alertview.AlertView;
import io.bhex.baselib.view.alertview.OnDismissListener;
import io.bhex.baselib.view.alertview.OnItemClickListener;
import io.bhex.sdk.account.UserInfo;
import io.bhex.sdk.account.bean.UserInfoBean;
import io.bhex.sdk.data_manager.RateDataManager;
import io.bhex.sdk.data_manager.SymbolDataManager;
import io.bhex.sdk.quote.bean.ChainType;
import io.bhex.sdk.quote.bean.CoinPairBean;
import io.bhex.sdk.trade.bean.AssetDataResponse;
import io.bhex.sdk.trade.bean.AssetListResponse;
import io.bhex.sdk.trade.bean.FeeBeanResponse;

/**
 * ================================================
 * 描   述：资产详情
 * ================================================
 */

public class AssetDetailActivity extends BaseActivity<AssetDetailPresenter, AssetDetailPresenter.AssetDetailUI> implements AssetDetailPresenter.AssetDetailUI, View.OnClickListener {
    private AssetListResponse.BalanceBean assetItemBean;
    private TopBar topBar;
    private View headerView;
    private TextView tokenFullName;
    private TextView tokenName;
    private TextView assetAvailable;
    private TextView assetFrozen;
    private TextView tokenAboutBtc;
    private TextView tokenAboutCurrenyTitle;
    private TextView tokenAboutCurreny;
    private LayoutInflater layoutInflater;
    private RelativeLayout rootView;
    private TextView assetTotal;
    private int digit;
    private String[] assetSheetArray;
    private AlertView assetAction;

    private ViewPager viewPager;
    private TabLayout tab;
    private ArrayList<Pair<String, Fragment>> items;
    private RecordAdapter recordAdapter;
    private SmartRefreshLayout swipeRefresh;

    private AssetRecordFragment assetRecordRecharge;
    private AssetRecordFragment assetRecordWithDraw;
    private AssetFlowFragment other;
    private FeeBeanResponse currentTokenFee;
    private String selectChainType="";

    @Override
    protected int getContentView() {
        return R.layout.activity_asset_detail_layout;
    }

    @Override
    protected AssetDetailPresenter createPresenter() {
        return new AssetDetailPresenter();
    }

    @Override
    protected AssetDetailPresenter.AssetDetailUI getUI() {
        return this;
    }

    @Override
    protected void initView() {
        super.initView();
//        assetSheetArray = new String[]{getString(R.string.btn_transfer),getString(R.string.string_recharge_coin),getString(R.string.string_withdraw_coin)};
        assetSheetArray = new String[]{getString(R.string.string_recharge_coin), getString(R.string.string_withdraw_coin), getString(R.string.string_title_address_manage)};
        Intent intent = getIntent();
        topBar = viewFinder.find(R.id.topBar);
        this.setTopbarNight(topBar);
        topBar.setRightImg(R.mipmap.icon_more_actions);
        topBar.setRightOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showAssetOperate();
            }
        });
        rootView = viewFinder.find(R.id.rootView);
        layoutInflater = LayoutInflater.from(this);
        headerView = viewFinder.find(R.id.header_asset_detail);
        swipeRefresh = viewFinder.find(R.id.swipeRefresh);


        if (intent != null) {
            assetItemBean = (AssetListResponse.BalanceBean) intent.getSerializableExtra(AppData.INTENT.KEY_ASSET);
            if (assetItemBean != null) {
                digit = AppData.Config.DIGIT_DEFAULT_VALUE;
                topBar.setTitle(assetItemBean.getTokenName());
                String iconUrl = assetItemBean.getIconUrl();
                if (!TextUtils.isEmpty(iconUrl)) {
                    ImageView icon = headerView.findViewById(R.id.coin_icon);
                    Glide.with(this).load(iconUrl).into(icon);
                }
                assetTotal = headerView.findViewById(R.id.asset_total);
                tokenFullName = headerView.findViewById(R.id.asset_token_fullname);
                tokenName = headerView.findViewById(R.id.asset_token);
                assetAvailable = headerView.findViewById(R.id.asset_available);
                assetFrozen = headerView.findViewById(R.id.asset_frozen);
                tokenAboutBtc = headerView.findViewById(R.id.asset_abount_btc);
                tokenAboutCurrenyTitle = headerView.findViewById(R.id.asset_abount_curreny_title);
                tokenAboutCurreny = headerView.findViewById(R.id.asset_abount_curreny);
                tokenFullName.setText(assetItemBean.getTokenFullName());
                tokenName.setText(assetItemBean.getTokenName());

                assetTotal.setText(NumberUtils.roundFormatDown(assetItemBean.getTotal(), digit));
                assetAvailable.setText(NumberUtils.roundFormatDown(assetItemBean.getFree(), digit));
                assetFrozen.setText(NumberUtils.roundFormatDown(assetItemBean.getLocked(), digit));
                tokenAboutBtc.setText(assetItemBean.getBtcValue());
                tokenAboutCurrenyTitle.setText(getString(R.string.string_abount_curreny, RateDataManager.CurRateCode()));
                tokenAboutCurreny.setText("≈" + RateDataManager.getShowLegalMoney(RateDataManager.CurRatePrice(AppData.Config.LEGAL_MONEY_ABOUT_VALUE_CAL_UNIT, assetItemBean.getBtcValue()), AppData.DIGIT_LEGAL_MONEY));
            }
        }


//        ShadowDrawable.setShadowCircle(viewFinder.find(R.id.icon_transfer), getResources().getColor(R.color.white), getResources().getColor(R.color.dark10));
//        ShadowDrawable.setShadowCircle(viewFinder.find(R.id.icon_deposit));
//        ShadowDrawable.setShadowCircle(viewFinder.find(R.id.icon_withdraw));
//        ShadowDrawable.setShadowCircle(viewFinder.find(R.id.icon_gotrade));
        CoinPairBean coinPairBean = SymbolDataManager.GetInstance().getSymbolByToken(assetItemBean.getTokenId());
        if(coinPairBean == null) {
            viewFinder.find(R.id.goTrade).setVisibility(View.GONE);
        }

        viewPager = viewFinder.find(R.id.viewPager);
        tab = viewFinder.find(R.id.tab);
        tab.setTabTextColors(this.getResources().getColor(CommonUtil.isBlackMode() ? R.color.dark_night : R.color.dark),this.getResources().getColor(R.color.blue));
        initFragmentTab();
    }

    private void initFragmentTab() {

        if (assetItemBean == null)
            return;
        items = new ArrayList<>();
        assetRecordRecharge = new AssetRecordFragment();
        Bundle bundle = new Bundle();
        bundle.putString(AssetRecordFragment.KEY_ASSET_TOKENID, assetItemBean.getTokenId());
        bundle.putInt(AppData.INTENT.KEY_RECORD_TYPE, 0);
        assetRecordRecharge.setArguments(bundle);

        assetRecordWithDraw = new AssetRecordFragment();
        Bundle bundle1 = new Bundle();
        bundle1.putInt(AppData.INTENT.KEY_RECORD_TYPE, 1);
        bundle1.putString(AssetRecordFragment.KEY_ASSET_TOKENID, assetItemBean.getTokenId());
        assetRecordWithDraw.setArguments(bundle1);

        other = new AssetFlowFragment();
        Bundle bundle2 = new Bundle();
        bundle2.putString(AssetRecordFragment.KEY_ASSET_TOKENID, assetItemBean.getTokenId());
        bundle2.putInt(AppData.INTENT.KEY_RECORD_TYPE, 2);
        other.setArguments(bundle2);


        items.add(new Pair<String, Fragment>(getString(R.string.string_recharge_coin), assetRecordRecharge));
        items.add(new Pair<String, Fragment>(getString(R.string.string_withdraw_coin), assetRecordWithDraw));
        items.add(new Pair<String, Fragment>(getString(R.string.string_other), other));
        if (recordAdapter == null) {

            recordAdapter = new RecordAdapter(getSupportFragmentManager());
            viewPager.setAdapter(recordAdapter);
            tab.setupWithViewPager(viewPager);
//        tab.setTabTextColors(getResources().getColor(R.color.color_white),getResources().getColor(R.color.color_black));
            tab.setTabMode(TabLayout.MODE_FIXED);
            tab.setTabGravity(TabLayout.GRAVITY_FILL);

            viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
                @Override
                public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

                }

                @Override
                public void onPageSelected(int position) {

                }

                @Override
                public void onPageScrollStateChanged(int state) {

                }
            });
        } else {
            recordAdapter.notifyDataSetChanged();
        }
        CommonUtil.setUpIndicatorWidthByReflex(tab, 15, 15);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (assetItemBean != null) {
            if (!NetWorkStatus.isConnected(this)) {
                ToastUtils.showShort(this, getResources().getString(R.string.hint_network_not_connect));
                return;
            }
            initChainTypeChoice(assetItemBean.getTokenId());
            if (UserInfo.isLogin())
                getPresenter().getAsset(assetItemBean.getTokenId());
                getPresenter().getQuotaInfo(assetItemBean.getTokenId(),selectChainType);
        }
    }

    /**
     * 初始化-连路类型选择
     * @param tokenId
     */
    private void initChainTypeChoice(String tokenId) {
        List<ChainType> chainTypes = SymbolDataManager.GetInstance().getTokenChainTypesByTokenId(tokenId);
        if (chainTypes != null&&chainTypes.size()>0) {
            //提币默认类型设置
            boolean isSetSelected = false;
            for (ChainType chainType : chainTypes) {
                if (!isSetSelected && chainType.isAllowWithdraw()) {
                    chainType.setSelect(true);
                    isSetSelected = true;
                    selectChainType = chainType.getChainType();
                } else {
                    chainType.setSelect(false);
                }
            }
        }
    }


    public void showAsset(AssetDataResponse.ArrayBean assetBean) {
        if (assetBean != null) {
            assetTotal.setText(NumberUtils.roundFormatDown(assetBean.getTotal(), digit));
            assetAvailable.setText(NumberUtils.roundFormatDown(assetBean.getFree(), digit));
            assetFrozen.setText(NumberUtils.roundFormatDown(assetBean.getLocked(), digit));
            tokenAboutBtc.setText(assetBean.getBtcValue());
            tokenAboutCurrenyTitle.setText(getString(R.string.string_abount_curreny, RateDataManager.CurRateCode()));
            tokenAboutCurreny.setText("≈" + RateDataManager.getShowLegalMoney(RateDataManager.CurRatePrice(AppData.Config.LEGAL_MONEY_ABOUT_VALUE_CAL_UNIT, assetBean.getBtcValue()), AppData.DIGIT_LEGAL_MONEY));

        }
    }

    @Override
    public void showFeeInfo(FeeBeanResponse response) {
        if (response != null) {
            currentTokenFee = response;
        }
    }

    private void showAssetOperate() {
        assetAction = new AlertView(null, null, getString(R.string.string_cancel), null, assetSheetArray, this, AlertView.Style.ActionSheet, new OnItemClickListener() {
            @Override
            public void onItemClick(Object o, int position) {
                if (position == -1) {
                    return;
                }
//                if (position == 0) {
//                    //转账
//                }else
                if (position == 0) {
                    //充币
                    deposite();
                } else if (position == 1) {
                    //提币
                    withdraw();
                } else if (position == 2) {
                    if (assetItemBean != null) {
                        IntentUtils.goCoinAddressList(AssetDetailActivity.this, "",assetItemBean.getTokenId(), assetItemBean.getTokenName(), assetItemBean.getIconUrl(), assetItemBean.getTokenFullName(), -5, assetItemBean.isNeedAddressTag());
                    }
                }
            }
        });
        assetAction.setOnDismissListener(new OnDismissListener() {
            @Override
            public void onDismiss(Object o) {
            }
        });
        assetAction.show();
    }

    @Override
    protected void addEvent() {
        super.addEvent();
        viewFinder.find(R.id.deposit).setOnClickListener(this);
        viewFinder.find(R.id.withdraw).setOnClickListener(this);
        viewFinder.find(R.id.transfer).setOnClickListener(this);
        viewFinder.find(R.id.goTrade).setOnClickListener(this);
        swipeRefresh.setOnRefreshListener(new OnRefreshListener() {

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                getPresenter().getAsset(assetItemBean.getTokenId());
                assetRecordRecharge.ActivityNotifyFragment();
                assetRecordWithDraw.ActivityNotifyFragment();
                other.ActivityNotifyFragment();
                refreshLayout.finishRefresh(1000);
            }
        });
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.transfer:
                //TODO 暂无功能
                if (assetItemBean != null) {
                    String tokenId = assetItemBean.getTokenId();
                    IntentUtils.goAssetTransfer(this,tokenId);
                }
                break;
            case R.id.deposit:
                deposite();
                break;
            case R.id.withdraw:
                withdraw();
                break;
            case R.id.goTrade:
                goTrade();
                break;
        }
    }

    private void goTrade() {
        if (assetItemBean != null) {
            CoinPairBean coinPairBean;
            //默认xxx/USDT币对
            coinPairBean = SymbolDataManager.GetInstance().getSymbolInfoById(assetItemBean.getTokenId()+"USDT");
            if (coinPairBean != null && !TextUtils.isEmpty(coinPairBean.getSymbolId())) {
            }else{
                //如果没有xxx/USDT币对,则查询相关tokenId的xxx/ 币对
                coinPairBean = SymbolDataManager.GetInstance().getSymbolByToken(assetItemBean.getTokenId());
            }
            if(coinPairBean != null && !TextUtils.isEmpty(coinPairBean.getSymbolId())) {
                coinPairBean.setNeedSwitchTradeTab(true);
                EventBus.getDefault().postSticky(coinPairBean);
                IntentUtils.goMain(AssetDetailActivity.this);
                finish();
            }else{
                //如果没有 则使用默认币对
                CoinPairBean defaultTradeCoinPair = SymbolDataManager.GetInstance().getDefaultTradeCoinPair();
                if(defaultTradeCoinPair != null && !TextUtils.isEmpty(defaultTradeCoinPair.getSymbolId())) {
                    coinPairBean.setNeedSwitchTradeTab(true);
                    EventBus.getDefault().postSticky(defaultTradeCoinPair);
                    IntentUtils.goMain(AssetDetailActivity.this);
                    finish();
                }else{
                    DebugLog.e("not default trade symbol");
                }

            }
        }
    }

    private void withdraw() {
        /**
         * 根据用户绑定新系统，提示用户是否可以提币
         */
        if (assetItemBean != null) {
            if (assetItemBean.isAllowWithdraw()) {
                if (currentTokenFee != null) {
                    if (!currentTokenFee.isAllowWithdraw()) {
                        DialogUtils.showDialogOneBtn(this, "", currentTokenFee.getRefuseReason(), getString(R.string.string_i_know), false, new DialogUtils.OnButtonEventListener() {
                            @Override
                            public void onConfirm() {
                            }

                            @Override
                            public void onCancel() {

                            }
                        });
                        return;
                    }
                }
                getPresenter().getUserInfo();
            } else {
                ToastUtils.showShort(this, getString(R.string.string_suspeng_withdraw));
            }
        } else {
            ToastUtils.showShort(this, getString(R.string.string_wait_retry));
        }
    }

    private void deposite() {
        if (assetItemBean != null) {
            if (assetItemBean.isAllowDeposit()) {
                IntentUtils.goRechargeCoin(this, assetItemBean);
            } else {
                ToastUtils.showShort(this, getString(R.string.string_suspeng_deposit));
            }
        } else {
            ToastUtils.showShort(this, getString(R.string.string_wait_retry));
        }
    }

    @Override
    public void requestUserInfoSuccess(final UserInfoBean userInfo) {
        if (userInfo != null) {
            IntentUtils.goWithDrawCoin(AssetDetailActivity.this, assetItemBean);
        }
    }


    private class RecordAdapter extends FragmentPagerAdapter {

        public RecordAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            return items.get(position).second;
        }

        @Override
        public int getCount() {
            return items.size();
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return items.get(position).first;
        }


    }
}
